package com.system.shiro;


import com.system.domain.Permission;
import com.system.domain.User;
import com.system.service.ShiroService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.List;

public class MyRealm extends AuthorizingRealm {

    private ShiroService shiroService;

    public ShiroService getShiroService() {
        return shiroService;
    }

    public void setShiroService(ShiroService shiroService) {
        this.shiroService = shiroService;
    }
    //授权的方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权的方法进来了");
        User user=(User) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        if(user!=null){
            List<Permission> permissionsByUser = shiroService.getPermissionsByUser(user);

            if (permissionsByUser.size()!=0) {
                for (Permission p: permissionsByUser) {

                    info.addStringPermission(p.getUrl());
                }
                return info;
            }

        }
        return null;
    }

    //认证的方法
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证的方法进来了");
        UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;
        System.out.println("token:"+token.getUsername());
        User user = shiroService.getUserByUserName(token.getUsername());
        if (user==null){
            //账号为空
            return null;
        }
         AuthenticationInfo info=new SimpleAuthenticationInfo(user,user.getPassword(),this.getClass().getSimpleName());
        return info;
    }



}
